import {
  ACCESS_TOKEN,
  APP_QUERY
} from '@/store/mutation-types'
import storage from '@/utils/storage'
import { loginMiniWX, loginMiniDY } from '@/api/login.js'
import { queryUserInfo } from '@/api/user.js'
import { queryMiniProgramInfo } from '@/api/index.js'
import { headerParams } from '@/config/headerParams.js'


// 登陆成功 后执行
const loginSuccess = (commit, data) => {
  const { token } = data
  // 过期时间30天
  const expiryTime = 30 * 86400
  // 保存tokne到缓存
  storage.set(ACCESS_TOKEN, token, expiryTime)
  // 记录到store全局变量
  commit('SET_TOKEN', token)
}

export const state = {
  // 用户认证token
  token: '',
  // 用户信息
  userInfo: { user_code: undefined, }
}

export const mutations = {
  SET_TOKEN: (state, value) => {
    state.token = value
  },
  SET_USER: (state, value) => {
    state.userInfo = value
  },
}

export const actions = {

  // 用户登录(普通登录: 输入账号、密码和验证码)
  Login({ commit }, code) {
    return new Promise((resolve, reject) => {
      // 获取巨量广告的参数
      const { query } = uni.getEnterOptionsSync()
			
      // #ifdef MP-TOUTIAO
      loginMiniDY({
        code,
        ...query
      }).then(data => {
        loginSuccess(commit, data)
        resolve(data)
      }).catch(reject)
      // #endif
    })
  },

  // 用户信息
  UserInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      // if (state.userInfo.user_code) {
      //   return resolve(state.userInfo)
      // }
      queryUserInfo().then(data => {
        commit('SET_USER', data)
        resolve(data)
      }).catch(reject)
    })
  },

}
